﻿using Microsoft.Extensions.DependencyInjection;
using Modules;
using PetaPoco;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;
using System.Reflection.Emit;

namespace PmSoft.Logging.Repositories;


/// <summary>
/// OperationLog仓储接口 
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class SysTableLogRepository : Repository<SysTableLog, LogDbContext>
{
    public SysTableLogRepository(LogDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext) { }

    public int Clean(DateTime? startDate, DateTime? endDate)
    {
        Sql builder = Sql.Builder;
        builder.Append("DELETE FROM sys_table_logs", new object[0]);
        if (startDate.HasValue)
        {
            builder.Where("create_time >= @0", new object[] { startDate.Value });
        }
        if (endDate.HasValue)
        {
            builder.Where("create_time <= @0", new object[] { endDate.Value });
        }
        return DbContext.Execute(builder);
    }

    public IPagedList<SysTableLog> GetLogs(SysTableLogQuery query, int pageIndex, int pageSize)
    {
        Sql builder = Sql.Builder;
        if (!string.IsNullOrEmpty(query.Keywords))
        {
            builder.Where("url LIKE @0 OR ip LIKE @0 OR data LIKE @0", new object[] { '%' + query.Keywords + '%' });
        }
        if (query.OperationType.HasValue)
        {
            builder.Where("operation_type = @0", query.OperationType);
        }
        if (!string.IsNullOrEmpty(query.OperatorName))
        {
            builder.Where("operator like @0", new object[] { "%" + query.OperatorName + "%" });
        }
        if (query.BeginTime.HasValue)
        {
            builder.Where("create_time >= @0", new object[] { ValueUtility.GetSafeSqlDateTime(query.BeginTime.Value) });
        }
        if (query.EndTime.HasValue)
        {
            builder.Where("create_time <= @0", new object[] { ValueUtility.GetSafeSqlDateTime(query.EndTime.Value) });
        }
        if (query.OperatorUserId.HasValue)
        {
            builder.Where("user_id = @0", new object[] { query.OperatorUserId.Value });
        }

        if (!string.IsNullOrEmpty(query.TableName))
        {
            builder.Where("table_name = @0", new object[] { query.TableName });
        }
        if (!string.IsNullOrEmpty(query.DatabaseName))
        {
            builder.Where("database_name = @0", new object[] { query.DatabaseName });
        }
        if (!string.IsNullOrEmpty(query.ObjectId))
        {
            builder.Where("object_id = @0", new object[] { query.ObjectId });
        }

        builder.OrderBy(new object[] { "id desc" });

        return GetPagingEntities(pageSize, pageIndex, builder);
    }
}

